
import {ref,reactive} from "vue"
import { http } from './http.js'
/**
 * 日期格式化函数
 * @param date 日期对象
 * @param format 日期格式，默认为 YYYY-MM-DD HH:mm:ss
 */
export const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  // 获取年月日时分秒，通过 padStart 补 0
  const year = String(date.getFullYear())
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  // 返回格式化后的结果
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}
/**
 * 获取年月日 时分秒
 * @returns {Object}
 */
export function getCurrentTime() {
  const d = new Date();
  let month = "" + (d.getMonth() + 1);
  let day = "" + d.getDate();
  const year = d.getFullYear();
  const hour = d.getHours() < 10 ? "0" + d.getHours() : d.getHours();
  const min = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes();
  const sec = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds();
  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;
  return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
}

/**
 * 将时间解析为字符串
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}
export const baseURL = "http://172.20.103.71:8000"
export const basePDFURL = "http://117.159.15.200:9795"

//获取当前年月日的时间戳
export function currentDate() {
  // 创建一个新的Date对象，它默认包含当前的日期和时间
  let now = new Date();

  // 设置小时、分钟、秒和毫秒为0，以获取当天的开始时间
  now.setHours(0, 0, 0, 0);

  // 使用getTime()方法获取这个时间的时间戳（毫秒）
  return now.getTime();
}
//扫码公共方法
export function onCan(callback){
  // #ifdef MP-DINGTALK
  dd.scan({
    type: "all", // 支持 qrCode、barCode、datamatrix 等
    success: async (res) => {
      try{
        await callback(res.code)
      }catch(err){
        uni.showToast({
          icon: "none",
          title: "扫码失败,请联系信息部",
        });
      }
      
    },
    fail: (err) => {
      console.error(err);
    },
  });
  // #endif

  // #ifdef APP-PLUS
  uni.scanCode({
    onlyFromCamera: false,
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true, // 自动解析字符集，解决中文乱码问题
    success: async (res) => {
      try{
        await callback(res.result)
      }catch(err){
        uni.showToast({
          icon: "none",
          title: "扫码失败,请联系信息部",
        });
      }
    },
    fail: (err) => {
      console.error(err);
    },
  });
  // #endif
}

//列表数据公共方法
export function commonListsFn(callback1,callback2,size=10){
  const loadStatus = ref("loadmore");
const query = ref({
  page: 0,
  size
});
const state = reactive({
  rows: [],
  totals: 0,
});
const loadData = async () => {
  if(!callback1) return
  let res=await callback1(query.value)
  console.log(res,"loadData")
  state.rows = [...state.rows, ...res.content];
  state.totals = res.totalElements;
  if (state.rows.length < state.totals) {
    loadStatus.value = "loadmore"; // 仍可继续上拉
  } else {
    loadStatus.value = "nomore"; // 已全部加载
  }
  callback2&&callback2()
  
};
const Consistentlogic = async () => {
  try {
    uni.showLoading({
      title: "加载中",
    });
    state.rows = [];
    state.totals = 0;
    await loadData();
  } finally {
    uni.hideLoading();
  }
};
const handleSearch = async() => {
  query.value.page = 0;
  await Consistentlogic();
};
const handlecancel = () => {
  query.value = {
    page: 0,
    size
  };
  Consistentlogic();
};
const handleloadMore = async () => {
  // 防止重复请求
  if (loadStatus.value === "loading") return;
  loadStatus.value = "loading";
  // 判断是否还有更多数据
  if (state.rows.length < state.totals) {
    loadStatus.value = "loadmore"; // 仍可继续上拉
    query.value.page += 1; // 为下一次请求准备页码
    try {
      await loadData();
    } catch (error) {
      console.log("加载数据失败", error);
    }
  } else {
    loadStatus.value = "nomore"; // 已全部加载
  }
};
function onScrollToBottom() {
  // 当 scroll-view 触底且状态为 loadmore 时手动调用
  if (loadStatus.value === "loadmore") {
    handleloadMore();
  }
}
return {query,state,loadStatus,handleSearch,handlecancel,onScrollToBottom}
}
